package com.ftg.learn.chapter03;

/**
 * 快乐数
 *
 * @author kangjx
 * @version 1.0
 * @date 2023/5/13 下午3:46
 */
public class HappyNum {

    /**
     * 是否为快乐数
     *
     * @param a 整数
     * @return true
     */
    public static boolean isHappy(int a) {

        int n = 0;
        while (a != 1) {

            int len = count(a);
            int temp = 0;
            for (int i = 0; i < len; i++) {
                int a1 = a / (int) (Math.pow(10, i)) % 10;
                temp += a1 * a1;
            }
            a = temp;
            //判断无循环
            if (n++ >= 100) {
                return false;
            }
        }
        return true;
    }

    /**
     * 求整数有几位
     *
     * @param n 正整数
     * @return
     */
    public static int count(int n) {
        int index = 0;
        while (n != 0) {
            n /= 10;
            index++;
        }
        return index;
    }

    public static void main(String[] args) {
        System.out.println(isHappy(550));
    }

}
